#!/usr/bin/python
# -*- coding: latin1 -*-

# $Id: imaptest 423 2011-06-09 15:16:44Z andre $

import imaplib
import getopt, sys
import getpass

def usage():
    print """
    imapconnect -s server -u username -p password

    server defaults to localhost
    username defaults to user that run utility

    """
def imapconnect(host='athena.cube.lan', user='u1@example.com', pwd='u1'):
    connection=imaplib.IMAP4(host)
    connection.login(user, pwd)
    return connection

try:
    opts, args = getopt.getopt(sys.argv[1:], "hs:u:p:", ["help", "server=", "user=", "password="])
except getopt.GetoptError, err:
    # print help information and exit:
    print str(err) # will print something like "option -a not recognized"
    sys.exit(2)

server='localhost'
user=getpass.getuser()
password=None

for o, a in opts:
    if o in ("-u", "--user"):
        user = a
    elif o in ("-s", "--server"):
        server = a
    elif o in ("-p", "--password"):
        password = a
    elif o in ("-h", "--help"):
        usage()
        sys.exit(2)
    else:
        assert False, "unhandled option"
if not password:
    password=getpass.getpass("%s's password:" % user)

print ">> trying to connect to server '%s' as '%s'." % (server, user)
try:
    c=imapconnect(host=server, user=user, pwd=password)
    stat, banner = c.capability()
except:
    stat='FAILED'

print ">> Status:%s" % stat
if stat == 'OK':
    print ">> CAPABILITIES:\n%s" % banner[0]
